import { Component, OnInit, Input, Output, EventEmitter, OnChanges } from '@angular/core';
import { Router, ActivatedRoute } from '@angular/router';
import { ListResult } from 'app/modules/base/api-base';
import { FormControl } from '@angular/forms';

@Component({
	selector: 'm-pagination',
	templateUrl: './pagination.component.html',
	styleUrls: ['./pagination.component.scss'],
})
export class PaginationComponent implements OnInit {
	constructor(private router: Router, private route: ActivatedRoute) {}
	@Input() length: number;
	@Input() pageSize = 10;
	@Input() page = 1;
	@Input() autoHidden = false;
	@Input() useRouteQuery = true;
	@Input() result: ListResult;

	pageSizeControl = new FormControl();

	@Output() pageChange = new EventEmitter<number>();

	ngOnInit() {
		// use page query param navigate
		if (this.useRouteQuery) {
			this.route.queryParamMap.subscribe(query => {
				const page = Number(query.get('page'));
				if (page === 0) {
					this.page = 1;
					this.pageChange.emit(this.page);
					return;
				}
				if (page !== this.page) {
					this.change(page);
				}
			});
		}
	}
	change(page: number) {
		if (this.useRouteQuery) {
			this.router.navigate([], { queryParams: { page }, queryParamsHandling: 'merge' });
		}
		this.pageChange.emit(page);
	}

	changeSize() {
		const page = 1;
		const count = this.pageSizeControl.value as Number;
		if (this.useRouteQuery) {
			this.router.navigate([], { queryParams: { page, count }, queryParamsHandling: 'merge' });
		}
		this.pageChange.emit(page);
	}
}
